<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="学校" prop="SchoolID">
          <el-input v-model="queryParams.SchoolID" placeholder="请输入学校" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="年级" prop="GradeID">
          <el-input v-model="queryParams.GradeID" placeholder="请输入年级" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd"
            v-hasPermi="['indicator:indicator:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
        </el-col>
        <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
      </el-row>
  
      <el-table border v-if="refreshTable" v-loading="loading" :data="indicatorList" row-key="parentIndicatorId"
        :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
  
        <el-table-column label="一级指标" prop="category" />
        <el-table-column label="指标等级" align="center" prop="level" width="80" />
        <!-- <el-table-column label="父id" align="center" prop="parentIndicatorId" /> -->
        <el-table-column label="指标名称" align="center" prop="description" show-overflow-tooltip />
        <!-- <el-table-column label="树编码" align="center" prop="treeCode" /> -->
        <!-- <el-table-column label="排序" align="center" prop="orderNum" /> -->
        <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
        <el-table-column label="权重" align="center" prop="weight" width="80" />
        <el-table-column label="学校" prop="schoolID" align="center" />
        <el-table-column label="年级" align="center" prop="gradeID" width="80" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleUpdate(scope.row)"
              v-hasPermi="['indicator:indicator:edit']">修改</el-button>
            <el-button link type="primary" @click="handleAdd(scope.row)"
              v-hasPermi="['indicator:indicator:add']">新增</el-button>
            <el-button link type="primary" @click="handleDelete(scope.row)"
              v-hasPermi="['indicator:indicator:remove']">删除</el-button>
            <!-- <el-button link type="primary" @click="handleAddCommit(scope.row)"
              v-hasPermi="['comment:comment:add']">添加评语</el-button> -->
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 添加或修改指标信息对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
        <el-form ref="indicatorRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="学校" prop="SchoolID">
            <el-input v-model="form.schoolID" placeholder="请输入学校" />
          </el-form-item>
          <el-form-item label="指标" prop="GradeID">
            <el-input v-model="form.category" placeholder="请输入指标" />
          </el-form-item>
          <el-form-item label="年级" prop="GradeID">
            <el-input v-model="form.gradeID" placeholder="请输入年级" />
          </el-form-item>
          <el-form-item label="水平" prop="level">
            <el-input v-model="form.level" placeholder="请输入水平" />
          </el-form-item>
          <el-form-item label="父id" prop="parentIndicatorId">
            <el-input v-model="form.parentIndicatorId" placeholder="请输入父id" />
          </el-form-item>
          <el-form-item label="指标名称" prop="description">
            <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="树编码" prop="treeCode">
            <el-tree-select v-model="form.treeCode" :data="indicatorOptions"
              :props="{ value: 'parentIndicatorId', label: 'description', children: 'children' }"
              value-key="parentIndicatorId" placeholder="请选择树编码" check-strictly />
          </el-form-item>
          <el-form-item label="排序" prop="orderNum">
            <el-input v-model="form.orderNum" placeholder="请输入排序" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="权重" prop="weight">
            <el-input v-model="form.weight" placeholder="请输入权重" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
  
      <!-- 添加或修改评价信息对话框 -->
      <el-dialog :title="title" v-model="opencommit" width="500px" append-to-body>
        <ul style="list-style-type: none; margin-top: -20px;">
          <span>已有评语字段,请不要重复填写</span>
          <li v-for="(range, index) in existingRanges" :key="index">
            起始分数: {{ range.scoreRangeStart }} - 结束分数: {{ range.scoreRangeEnd }}
          </li>
        </ul>
        <el-form ref="commentRef" :model="formcommit" :rules="rulescommit" label-width="80px">
          <el-form-item label="开始分数" prop="scoreRangeStart">
            <el-input v-model="formcommit.scoreRangeStart" placeholder="请输入开始分数" />
          </el-form-item>
          <el-form-item label="结束分数" prop="scoreRangeEnd">
            <el-input v-model="formcommit.scoreRangeEnd" placeholder="请输入结束分数" />
          </el-form-item>
          <el-form-item label="评价" prop="comment">
            <el-input v-model="formcommit.comment" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitFormCommit">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup name="Indicator">
  import { listIndicator, getIndicator, delIndicator, addIndicator, updateIndicator } from "@/api/indicator/indicator";
  
  const { proxy } = getCurrentInstance();
  // 字典信息
  const { grade_name, class_name, school_name } = proxy.useDict('grade_name', 'class_name', 'school_name');
  const indicatorList = ref([]);
  const indicatorOptions = ref([]);
  const open = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const title = ref("");
  const isExpandAll = ref(true);
  const refreshTable = ref(true);
  
  const data = reactive({
    form: {},
    queryParams: {
      schoolID: null,
      gradeID: null,
      category: null,
      level: null,
      parentIndicatorId: null,
      description: null,
      treeCode: null,
      orderNum: null,
      weight: null,
      CreatedAt: null,
      UpdatedAt: null
    },
    rules: {
      schoolID: [
        { required: true, message: "学校不能为空", trigger: "blur" }
      ],
      gradeID: [
        { required: true, message: "年级不能为空", trigger: "blur" }
      ],
      category: [
        { required: true, message: "指标不能为空", trigger: "blur" }
      ],
      level: [
        { required: true, message: "水平不能为空", trigger: "blur" }
      ],
      description: [
        { required: true, message: "指标名称不能为空", trigger: "blur" }
      ],
      treeCode: [
        { required: true, message: "树编码不能为空", trigger: "blur" }
      ],
    }
  });
  
  const { queryParams, form, rules } = toRefs(data);
  
  /** 查询指标信息列表 */
  function getList() {
    loading.value = true;
    listIndicator(queryParams.value).then(response => {
      indicatorList.value = proxy.handleTree(response.data, "treeCode", "parentIndicatorId");
      loading.value = false;
    });
  }
  
  /** 查询指标信息下拉树结构 */
  function getTreeselect() {
    listIndicator().then(response => {
      indicatorOptions.value = [];
      const data = { parentIndicatorId: 0, description: '顶级节点', children: [] };
      data.children = proxy.handleTree(response.data, "treeCode", "parentIndicatorId");
      indicatorOptions.value.push(data);
    });
  }
  
  // 取消按钮
  function cancel() {
    open.value = false;
    opencommit.value = false;
    resetCommit();
    reset();
  }
  
  // 表单重置
  function reset() {
    form.value = {
      indicatorId: null,
      SchoolID: null,
      GradeID: null,
      category: null,
      level: null,
      parentIndicatorId: null,
      description: null,
      treeCode: null,
      orderNum: null,
      remark: null,
      weight: null,
      CreatedAt: null,
      UpdatedAt: null
    };
    proxy.resetForm("indicatorRef");
  }
  
  /** 搜索按钮操作 */
  function handleQuery() {
    getList();
  }
  
  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
  }
  
  /** 新增按钮操作 */
  function handleAdd(row) {
    reset();
    getTreeselect();
    if (row != null && row.parentIndicatorId) {
      form.value.treeCode = row.parentIndicatorId;
    } else {
      form.value.treeCode = 0;
    }
    open.value = true;
    title.value = "添加指标信息";
  }
  
  /** 展开/折叠操作 */
  function toggleExpandAll() {
    refreshTable.value = false;
    isExpandAll.value = !isExpandAll.value;
    nextTick(() => {
      refreshTable.value = true;
    });
  }
  
  /** 修改按钮操作 */
  async function handleUpdate(row) {
    reset();
    await getTreeselect();
    if (row != null) {
      form.value.treeCode = row.treeCode;
    }
    getIndicator(row.indicatorId).then(response => {
      form.value = response.data;
      open.value = true;
      title.value = "修改指标信息";
    });
  }
  
  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["indicatorRef"].validate(valid => {
      if (valid) {
        if (form.value.indicatorId != null) {
          updateIndicator(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addIndicator(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    });
  }
  
  /** 删除按钮操作 */
  function handleDelete(row) {
    proxy.$modal.confirm('是否确认删除指标信息编号为"' + row.indicatorId + '"的数据项？').then(function () {
      return delIndicator(row.indicatorId);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
  }
  
  getList();
  
  /**
  * 添加新增评语功能
  */
  
  
  const datacommit = reactive({
    formcommit: {},
    rulescommit: {
      scoreRangeStart: [
        { required: true, message: "开始时间不能为空", trigger: "blur" }
      ],
      scoreRangeEnd: [
        { required: true, message: "结束时间不能为空", trigger: "blur" }
      ],
      comment: [
        { required: true, message: "评价不能为空", trigger: "blur" }
      ]
    }
  });
  
  const { formcommit, rulescommit } = toRefs(datacommit);
  
  const opencommit = ref(false);
  import { addComment, listComment } from "@/api/comment/comment";
  import { ref } from "vue";
  
  const committotal = ref(0);
  const existingRanges = ref([]); // 用于存储转换后的分数段
  /** 查询已经有的评价分数*/
  function selectCommit(treeCode) {
    existingRanges.value = [];
    listComment().then(response => {
      // 转换为所需的格式
      existingRanges.value = response.rows
        .filter(comment => comment.treeCode === treeCode)
        .map(comment => ({
          scoreRangeStart: comment.scoreRangeStart,
          scoreRangeEnd: comment.scoreRangeEnd
        }));
      committotal.value = response.total;
    });
  }
  
  function handleAddCommit(row) {
    resetCommit();
    existingRanges.value = [];
    formcommit.value.treeCode = row.treeCode;
    formcommit.value.indicatorId = row.indicatorId;
    formcommit.value.description = row.description;
    formcommit.value.level = row.level;
    form.value.indicatorId = row.indicatorId;
    selectCommit(row.treeCode);
    opencommit.value = true;
    title.value = "添加评价信息";
  }
  // 表单重置
  function resetCommit() {
    formcommit.value = {
      commentId: null,
      indicatorId: null,
      scoreRangeStart: null,
      scoreRangeEnd: null,
      comment: null,
      level: null,
      treeCode: null,
      description: null,
      CreatedAt: null,
      UpdatedAt: null
    };
    existingRanges.value = [];
    proxy.resetForm("commentRef");
  }
  
  /** 提交按钮 */
  function submitFormCommit() {
  
    proxy.$refs["commentRef"].validate(valid => {
      // 1. 验证开始分数不能大于结束分数
      if (formcommit.value.scoreRangeStart >= formcommit.value.scoreRangeEnd) {
        proxy.$modal.msgError("开始分数不能大于结束分数");
        return;
      }
  
      // 2. 验证分数不能小于0
      if (formcommit.value.scoreRangeStart < 0 || formcommit.value.scoreRangeEnd < 0) {
        proxy.$modal.msgError("开始分数或结束分数不能小于0");
        return;
      }
  
      // 3. 验证分数不能大于10
      if (formcommit.value.scoreRangeStart > 10 || formcommit.value.scoreRangeEnd > 10) {
        proxy.$modal.msgError("开始分数或结束分数不能大于10");
        return;
      }
  
      // 4. 验证与已存在的分数段不冲突
      const existingRanges = [
        // 假设从后端获取的分数段
        { start_score: 1, end_score: 3 },
        { start_score: 4, end_score: 6 },
        { start_score: 7, end_score: 10 }
      ];
  
      for (const range of existingRanges) {
        if (
          (formcommit.value.scoreRangeStart >= range.start_score && formcommit.value.scoreRangeStart <= range.end_score) || // 新段起始分数在已有段内
          (formcommit.value.scoreRangeEnd >= range.start_score && formcommit.value.scoreRangeEnd <= range.end_score) ||     // 新段结束分数在已有段内
          (formcommit.value.scoreRangeStart <= range.start_score && formcommit.value.scoreRangeEnd >= range.end_score)      // 新段完全包含已有段
        ) {
          proxy.$modal.msgError("新分数段与已存在的分数段冲突");
          return;
        }
      }
  
      // 5. 验证通过，可以进行后续操作
      addComment(formcommit.value).then(response => {
        proxy.$modal.msgSuccess("新增成功");
      });
    });
  }
  
  </script>
  